<template>

  <div class="app-container">

    <!-- 过滤搜索框 START-->
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="角色名" v-model="filter.columns.role">
      </el-input>
      <el-select @change="handleFilter" clearable style="width: 120px" class="filter-item" v-model="filter.columns.isDelete" placeholder="角色状态">
        <el-option label="启用" :value="false"></el-option>
        <el-option label="禁用" :value="true"></el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
      <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>
    <!-- 过滤搜索框 END -->

    <!-- 表格呈现 START -->
    <el-table ref="demoTable" @selection-change="handleSelectionChange" element-loading-text="加载中" v-loading="listLoading" fit highlight-current-row border :data="list">
      <el-table-column prop="index" type="index"></el-table-column>
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="role" label="角色" width="120"></el-table-column>
      <el-table-column prop="level" align="center" label="等级" width="60"></el-table-column>
      <el-table-column label="角色状态" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isDelete | deleteFilter">{{scope.row.isDelete == false ? '启用':'禁用'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="角色描述" prop="description"></el-table-column>

      <!-- 详情展开内容 START -->
      <el-table-column type="expand" label="详情" width="80">
        <template slot-scope="props">
          <el-form label-position="left" inline label-width="80">

            <div v-for="permission in props.row.permissions" :key="permission.id">
              <el-form-item label="权限标识">
                <span>{{ permission.permission }}</span>
              </el-form-item>
              <el-form-item label="权限描述">
                <span>{{ permission.description }}</span>
              </el-form-item>
              <el-form-item label="权限状态">
                <el-tag :type="permission.isDelete | deleteFilter">{{permission.isDelete == false ? '启用':'禁用'}}</el-tag>
              </el-form-item>
            </div>
          </el-form>
        </template>
      </el-table-column>
      <!-- 详情展开内容 END -->

      <el-table-column align="center" label="操作" width="230">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格呈现 END -->

    <!-- 分页导航栏 START -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10, 25, 50, 100]" :pager-count="11" :total="total" layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 分页导航栏 END -->

    <!-- 编辑信息弹出框 START -->
    <el-dialog v-el-drag-dialog @dragDialog="handleDrag" :title="dialogTitle[dialogStatus]" :visible.sync="dialogVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px">
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" :rows="2" placeholder="请输入角色描述" v-model.number="temp.description"> </el-input>
        </el-form-item>
        <el-form-item label="角色名" prop="role">
          <el-input placeholder="请输入角色名" v-model="temp.role"> </el-input>
        </el-form-item>
        <el-form-item label="角色状态" prop="isDelete">
          <el-radio v-model="temp.isDelete" :label="false" border>启用</el-radio>
          <el-radio v-model="temp.isDelete" :label="true" border>禁用</el-radio>
        </el-form-item>
        <el-form-item label="角色等级" prop="level">
          <el-input type="number" max="2" placeholder="请输入手机号" v-model.number="temp.level"></el-input>
        </el-form-item>

        <div v-for="permission in temp.permissions" :key="permission.id">
          <el-form-item label="权限">
            <el-row>
              <el-col span="8">标识:
                <el-input disabled="disabled" v-model="permission.permission"></el-input>
              </el-col>
              <el-col span="8">描述:
                <el-input disabled="disabled" v-model="permission.description"></el-input>
              </el-col>
              <el-col span="8">状态:
                <el-select disabled="disabled" v-model="permission.isDelete">
                  <el-option :value="false" label="启用"></el-option>
                  <el-option :value="true" label="禁用"></el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button :disabled="dialogLoading" v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button :disabled="dialogLoading" v-else type="primary" @click="updateData">修改</el-button>
      </div>
    </el-dialog>
    <!-- 编辑信息弹出框 END -->

  </div>
</template>

<script>
import apiRole from '@/api/admin/role.js'
import waves from '@/directive/waves' // 水波纹特效 指令
import { getToken } from '@/utils/auth'
import elDragDialog from '@/directive/el-dragDialog' // base on element-ui

export default {
  name: 'account',
  components: {},
  directives: { waves, elDragDialog },
  data() {
    return {
      importFileUrl: process.env.BASE_API + '/upload',
      upLoadData: {
        path: 'test'
      },
      downloadLoading: false,
      total: 0,
      // 临时对象,用于编辑修改操作
      temp: {},
      // 弹出框表单状态
      dialogStatus: undefined,
      dialogTitle: {
        create: '创建角色',
        update: '修改角色'
      },
      dialogVisible: false,
      dialogLoading: false,
      // 编辑框校验规则
      rules: {
        role: [
          { required: true, message: '角色名必填', trigger: 'change' },
          { min: 1, max: 25, message: '长度在 1 到 25 个字符' },
          { pattern: /^[a-z]+$/, message: '角色名必须为小写英文字母', trigger: 'blur' }
        ]
      },
      list: [],
      listLoading: true,
      // 查询条件
      listQuery: {
        page: 1,
        size: 10,
        // 默认按照角色等级排序
        sorts: ['+level'],
        columns: {}
      },
      // 过滤框条件
      filter: {
        columns: {
          role: undefined,
          isDelete: undefined
        }
      },
      // 多选框选中对象
      multipleSelection: []
    }
  },
  watch: {
    listQuery: {
      handler(val) {
        this.getData(val)
      },
      deep: true
    }
  },
  filters: {
    deleteFilter(isDelete) {
      const deleteMap = {
        'true': 'danger',
        'false': 'success'
      }
      return deleteMap[isDelete]
    }
  },
  methods: {
    // v-el-drag-dialog onDrag callback function
    handleDrag() {
      this.$refs.select.blur()
    },
    // 上传成功后的回调
    uploadSuccess(response, file, fileList) {
      this.$notify({ title: '成功', message: '上传成功', type: 'success', duration: 2000 })
    },
    // 上传错误
    uploadError(response, file, fileList) {
      this.$notify({ title: '失败', message: '上传失败', type: 'error', duration: 2000 })
    },
    // 上传前对文件的大小的判断
    beforeAvatarUpload(file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const extension3 = file.name.split('.')[1] === 'doc'
      const extension4 = file.name.split('.')[1] === 'docx'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!extension && !extension2 && !extension3 && !extension4) {
        console.log('上传模板只能是 xls、xlsx、doc、docx 格式!')
      }
      if (!isLt2M) {
        console.log('上传模板大小不能超过 10MB!')
      }
      return extension || extension2 || extension3 || extension4 && isLt2M
    },
    filterSex(value, row) {
      return row.sex === value
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogVisible = true
      this.dialogLoading = false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        level: 2,
        description: undefined,
        isDelete: false,
        role: undefined
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogLoading = true
          apiRole.create(this.temp).then(res => {
            this.dialogLoading = false
            // 状态为成功
            if (res.status === 200) {
              this.dialogVisible = false
              // 数据直接插入表格顶部
              this.list.unshift(this.temp)
              this.$notify({ title: '成功', message: '创建成功', type: 'success', duration: 2000 })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogLoading = false
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      // 复制对象
      const tempData = Object.assign({}, this.temp)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogLoading = true
          apiRole.update(tempData).then(res => {
            this.dialogLoading = false
            if (res.status === 200) {
              this.dialogVisible = false
              this.$notify({ title: '成功', message: '更新成功', type: 'success', duration: 2000 })
              // 将修改后的对象替换进列表中
              for (const item of this.list) {
                if (item.id === this.temp.id) {
                  const index = this.list.indexOf(item)
                  this.list.splice(index, 1, tempData)
                  break
                }
              }
            }
          })
        }
      })
    },
    handleDelete(row) {
      // apiRole.remove(row).then(res => {
      //   if (res.status === 200) {
      //     this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
      //     const index = this.list.indexOf(row)
      //     this.list.splice(index, 1)
      //   }
      // })
    },
    handleDeleteMulti() {
      // const rows = this.multipleSelection
      // const params = Array(0)
      // rows.forEach(row => {
      //   params.push(row.id)
      // })

      // if (params.length > 0) {
      //   apiRole.removeMulti(params).then(res => {
      //     if (res.status === 200) {
      //       this.$message({
      //         message: res.data,
      //         type: 'success'
      //       })
      //       rows.forEach(row => {
      //         const index = this.list.indexOf(row)
      //         this.list.splice(index, 1)
      //       })
      //     }
      //   })
      // } else {
      //   this.$message({
      //     message: '请先勾选列表',
      //     type: 'warning'
      //   })
      // }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(this.multipleSelection)
    },
    handleSizeChange(size) {
      this.listQuery.size = size
    },
    handleCurrentChange(page) {
      this.listQuery.page = page
    },
    getData() {
      this.listLoading = true
      apiRole.search(this.listQuery).then(res => {
        this.listLoading = false
        if (res.status === 200) {
          this.list = res.data.list
          this.total = res.data.total
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.listQuery.columns = JSON.parse(JSON.stringify(this.filter.columns))
      // 昵称字段模糊搜索
      if (this.listQuery.columns.nickname && this.listQuery.columns.nickname !== '') {
        this.listQuery.columns.nickname = '%' + this.listQuery.columns.nickname + '%'
      }
      this.getData()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['主键', '角色', '角色状态', '描述']
        const filterVal = ['id', 'role', 'isDelete', 'description']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '角色表格'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'isDelete') {
          return v[j] === false ? '启用' : '禁用'
        } else {
          return v[j]
        }
      }))
    }
  },
  computed: {
    tokenHeader: function() {
      return { 'X-token': getToken() }
    }
  },
  created: function() {
    this.getData(this.listQuery)
  },
  mounted: function() {
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.documentation-container {
  margin: 50px;
  .document-btn {
    float: left;
    margin-left: 50px;
    display: block;
    background: black;
    color: white;
    height: 60px;
    width: 200px;
    line-height: 60px;
    font-size: 20px;
    text-align: center;
  }
}
</style>
